package com.example.kotlin.download

import android.Manifest
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import com.example.kotlin.R

class DownloadActivity : AppCompatActivity() {
    private val url = "http://wap.yesky.com/uploadImages/2013/265/247Y7IN74W47.png"
    private var downloadBinder: DownloadBinder? = null
    private var connection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            downloadBinder = service as DownloadBinder
        }

        override fun onServiceDisconnected(name: ComponentName?) {

        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_download)
    }

    fun startDownload(view: View) {

        val intent = Intent(this, DownloadService::class.java)
        startService(intent)
        bindService(intent, connection, BIND_AUTO_CREATE)
        //开启权限
        var permissionCheck: Int =
            this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
        permissionCheck += this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        //未获得位置权限
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {

            this.requestPermissions(
                arrayOf(
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ),
               1
            )
        } else {
            downloadBinder?.startDownload(url)
        }
//        if (ContextCompat.checkSelfPermission(
//                this,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE
//            ) != PackageManager.PERMISSION_GRANTED
//        ) {
//            ActivityCompat.requestPermissions(
//                this,
//                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
//                1
//            )
//        } else {
//            downloadBinder?.startDownload(url)
//        }


    }

    fun pauseDownload(view: View) {
        downloadBinder?.pauseDownLoad()
    }

    fun stopDownload(view: View) {
        downloadBinder?.cancelDownLoad()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (requestCode == 1) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                downloadBinder?.startDownload(url)
            }
        }
    }

    private fun getNotificationManager() =
        getSystemService(NOTIFICATION_SERVICE) as NotificationManager

    private fun getNotification(title: String): Notification {
        val channelId = "default"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            val channel =
                NotificationChannel(channelId, channelId, NotificationManager.IMPORTANCE_DEFAULT)
            val nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            nm?.let {
                if (it.getNotificationChannel(channelId) == null) {//没有创建
                    it.createNotificationChannel(channel)//则先创建
                }
            }
        }
        val intent = Intent(this, DownloadActivity::class.java)
        val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
        val builder: NotificationCompat.Builder = NotificationCompat.Builder(this, channelId)
        builder.setSmallIcon(R.mipmap.ic_launcher)
        builder.setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher))
        builder.setContentIntent(pendingIntent)
        builder.setContentTitle(title)
        return builder.build()


    }

    fun showNotification(view: View) {

        getNotificationManager().notify(1, getNotification("显示通知"))


    }
}
